﻿using ApiManage.Core.Utils;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Rhonin.Common.Components;
using Rhonin.Common.Extentions;
using Rhonin.Common.Logging;
using System;
using System.Diagnostics;
using ApiManage.Svc.Controllers;
using Rhonin.Common.Entity.UserTicket;

namespace ApiManage.Svc.Filter
{
    /// <inheritdoc />
    /// <summary>
    /// </summary>
    public class LogFilterAttribute : ActionFilterAttribute
    {
        private readonly ILogger _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(typeof(LogFilterAttribute).FullName);
        private Stopwatch _watch;
        private string _id;
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var ticket = BaseController.Ticket;
            var loginUser = ticket?.CUI;
            _watch = new Stopwatch();
            _watch.Start();
            _id = Guid.NewGuid().ToString("N");
            var routeData = (RouteData)actionContext.Controller.GetPropertyValue("RouteData");
            _logger.InfoFormat("\r\n----------↓↓↓↓↓请求开始↓↓↓↓↓----------\r\nid:【{3}】\r\nController：【{0}】\r\nAction：【{1}】\r\n参数信息：【{2}】\r\n操作用户：【{4}】",
                routeData.Values["controller"],
                routeData.Values["action"], actionContext.ActionArguments.Serialize(),
                _id,
                loginUser.Serialize());
            base.OnActionExecuting(actionContext);
        }
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            var value = actionExecutedContext.Result.GetPropertyValue("Value");
            base.OnActionExecuted(actionExecutedContext);
            _watch.Stop();
            _logger.InfoFormat("\r\nid:【{1}】\r\n总共处理时间为：【{0}ms】\r\n返回结果：【{2}】\r\n----------↑↑↑↑↑请求结束↑↑↑↑↑----------",
                _watch.ElapsedMilliseconds,
                _id,
                value.Serialize()
            );
        }
    }
}
